﻿using System.Diagnostics;
using System.Text;

namespace ProjectEuler
{
    public class Problem24
    {
        private int[] nums = new[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        int max = 1000000;

        public void Solve()
        {
          
            var currI = 0;
            var permCnt = 0;

            var perms = Perm(0, 0);

            Debug.WriteLine("Problem 24: " + perms);
        }

        int Perm(int index, int permCnt)
        {
            var currI = index + 1;

            var factorial = Common.FactorialAsNum(nums.Length - index - 1);
            
            while (permCnt + factorial < max)
            {
                Swap(index, currI);
                currI++;
                permCnt += factorial;
            }

            if (permCnt + factorial + Common.FactorialAsNum(nums.Length - index - 2) == max)
                return permCnt;

            return Perm(++index, permCnt);
        }

        void Swap(int i1, int i2)
        {
            Debug.Assert(i1 > -1 && i1 < nums.Length);
            Debug.Assert(i2 > -1 && i2 < nums.Length);
            Debug.Assert(i1 != i2);

            var tmp = nums[i1];
            nums[i1] = nums[i2];
            nums[i2] = tmp;

            TraceNumns();
        }

        void TraceNumns()
        {
            var sb = new StringBuilder();
            foreach (var num in nums)
            {
                sb.Append(num);
            }
            Debug.WriteLine(sb);
        }
    }
}